package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;

@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "ly.auth", name = {"clientId", "secret"})
@EnableConfigurationProperties(ClientProperties.class)
@EnableFeignClients(basePackages = "com.leyou.auth.client")
public class AuthConfiguration {

    private final AuthClient authClient;

    private final ClientProperties clientProperties;

    public AuthConfiguration(AuthClient authClient, ClientProperties clientProperties){
        this.authClient = authClient;
        this.clientProperties = clientProperties;
    }


    @Bean
    @Primary
    public JwtUtils jwtUtils(){

        try {
            String key = authClient.getSecretKey(clientProperties.getClientId(), clientProperties.getSecret());

            JwtUtils jwtUtils = new JwtUtils(key);
            log.info("密匙加载成功");
            return jwtUtils;
        } catch (Exception e) {
            log.info("初始化jwtutils失败,{}", e.getMessage());
            throw e;
        }

    }


}
